package cn.cellcom.agent.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.cellcom.agent.biz.TUserBiz;
import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.pojo.TOrg;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.agent.util.RedisManager;
import cn.cellcom.jar.dao.IBaseDao;
import cn.cellcom.jar.env.Env;
import cn.cellcom.jar.logon.LogonForm;
import cn.cellcom.jar.logon.LogonSession;
import cn.cellcom.jar.logon.LogonUtil;
import cn.cellcom.jar.util.CU;
import cn.cellcom.jar.util.CopyUtil;
import cn.cellcom.jar.util.DT;
import cn.cellcom.jar.util.LogUtil;
import cn.cellcom.jar.util.MD5;
import cn.cellcom.jar.util.MyException;

/**
 * 系统用户登陆的范例
 * 
 * @author 郑余杰
 */
public class LogonDpAct extends DispatchAction {

	private Log log = LogFactory.getLog(this.getClass());

	private TUserBiz ubiz;

	private IBaseDao dao;

	/**
	 * 空心跳
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward beat(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		return null;
	}

	public ActionForward logon(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		LogonForm fm = (LogonForm) form;

		TUser user;
		Object result;
		try {
			LogUtil.i(this.clazz, "登陆：" + fm.toString() + " from " + req.getRemoteAddr());
			LogonUtil.PasswordError = "您输入的密码不正确";
			LogonUtil.ValidateError = "您输入的验证码无效，请重输";
			result = LogonUtil.template(req, fm, dao, TUser.class, "username", "password", "status");
			if (result == null || result instanceof String) {
				ActionForward r = LogUtil.e(this.clazz, "登录失败，" + result, null, mapping, req);
				if(req.getParameter("ajax").equals("true")) {
					Response.err(rep, String.valueOf(result));
					return null;
				}
				return r;
			} else {
				user = (TUser) result;
			}
			LogonSession ls = new LogonSession(req);
			ls.logon(result);

			TOrg org = (TOrg) this.dao.myGet(TOrg.class, user.getOrg());
			req.getSession().setAttribute("org", org);

			if (org.getFirstLogon() == null) {
				ls.setAttribute("firstLogon", true);
				org.setFirstLogon(DT.getNow());
				this.dao.myUpdate(org);
			} else {
				// ls.setAttribute("firstLogon", false);
			}

			String token = MD5.toMd5(user.getUsername() + user.getUsername());
			RedisManager.getInstance().getToken().putAndExpireString(token, user.getUsername(), DT.ADAY);
			req.getSession().setAttribute("token", token);
			if(req.getParameter("ajax").equals("true")) {
				Response.succ(rep, "");
				return null;
			}
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "登录验证出现错误", e, mapping, req);
		}
		// 采用坐席URL登陆，或者坐席角色登陆，则直接进入坐席界面
		if (AgentConstant.AGENT_LOGIN.equals(fm.getOther()) || AgentConstant.USER_TYPE_AGENT.equals(user.getType())) {
			return mapping.findForward("agent");
		}
		return mapping.findForward("main");
	}

	public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		LogonSession ls = new LogonSession(req);
		try {
			ls.logout(rep, "../index.html", false);// 退出方法，可自定义要跳转到的页面
		} catch (MyException e) {
			log.error("用户退出操作出现错误", e.getException());
		}
		return mapping.findForward("logon");
	}

	/**
	 * 获取一个需要用户输入的验证码，如这样调用即可： <img id="validate" border=0
	 * src="user/LogonDpAct.do?method=getValidateNumber" />
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward getValidateNumber(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		LogonSession ls = new LogonSession(req);
		try {
			ls.generateValidate(req, rep);
		} catch (MyException e) {
			log.error("生成用户登陆验证码错误", e.getException());
		}// 生成一个图片，并以流输出
		return null;
	}

	public ActionForward doModifySelfPassword(ActionMapping mapping, ActionForm fm, HttpServletRequest req, HttpServletResponse rep) {
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();
		LogonForm of = (LogonForm) fm;
		if (!StringUtils.equals(of.getOldpassword(), user.getPassword())) {
			return LogUtil.e(this.clazz, "输入的旧密码不正确，", null, mapping, req);
		}
		if (!StringUtils.equals(of.getNewpassword(), of.getNewpassword2())) {
			return LogUtil.e(this.clazz, "输入的新的两次密码不一致，", null, mapping, req);
		}
		try {
			user.setPassword(of.getNewpassword());
			dao.myUpdate(user);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "密码修改失败", e, mapping, req);
		}
		req.setAttribute(Env.RESULT, "密码修改成功");
		return mapping.findForward("success");
	}

	/**
	 * 修改个人资料
	 * 
	 * @param mapping
	 * @param fm
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward doModifySelfInfo(ActionMapping mapping, ActionForm fm, HttpServletRequest req, HttpServletResponse rep) {
		LogonSession ls = new LogonSession(req);
		TUser user = (TUser) ls.getLogonObject();
		try {
			CopyUtil.copy(req, user, null, false);
			this.dao.myUpdate(user);

			ls.logon(user);
		} catch (MyException e) {
			return LogUtil.e(this.clazz, "个人信息修改失败", e, mapping, req);
		}

		req.setAttribute(Env.RESULT, "个人信息修改成功");
		return mapping.findForward("success");
	}

	/**
	 * 判断是否存在
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward isExist(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		LogonForm fm = (LogonForm) form;
		LogonSession ls = new LogonSession(req);

		String r = "您的信息有效，请即刻注册吧！";
		if (!LogonUtil.isValidate(ls, fm, LogonSession.VALIDATE)) {
			r = "验证码不正确，请重新输入";
		} else {
			if (!CU.isUsername(fm.getUsername(), 4, 20, false)) {
				r = "用户名必须是4-20位的英文字母";
			} else {
				String username = req.getParameter("username");
				String phone = req.getParameter("phone");
				String email = req.getParameter("email");
				try {
					TUser user = ubiz.get(username, phone);
					if (user != null) {
						r = user.getUsername().equals(username) ? "登陆账号已经被使用" : r;
						r = user.getPhone().equals(phone) ? "手机号码已经被使用" : r;
						r = user.getEmail().equals(email) ? "电子邮箱已经被使用" : r;
					}
				} catch (MyException e) {
					LogUtil.e(this.clazz, "注册失败，请联系我们", e, mapping, req);
					r = "注册失败，请联系我们";
				}
			}
		}
		Response.err(rep, r);
		return null;
	}

	/**
	 * 注册，写入表
	 * 
	 * @param mapping
	 * @param form
	 * @param req
	 * @param rep
	 * @return
	 */
	public ActionForward register(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse rep) {
		if (!LogonUtil.isValidate(new LogonSession(req), (LogonForm) form, LogonSession.VALIDATE)) {
			Response.err(rep, LogUtil.e(this.clazz, "请输入有效的验证码"));
			return null;
		}
		String org = req.getParameter("org");
		String phone = req.getParameter("phone");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		if (StringUtils.isBlank(org) || StringUtils.isBlank(phone) || StringUtils.isBlank(password)) {
			Response.err(rep, LogUtil.e(this.clazz, "请输入完整的信息哦"));
			return null;
		}
		String username = phone;// 注册采用电话号码作为账号
		try {
			TUser user = ubiz.get(username, phone);
			if (user != null) {
				String r = "手机号码已经被使用";
				Response.err(rep, LogUtil.e(this.clazz, r));
				return null;
			}
		} catch (MyException e) {
			Response.err(rep, LogUtil.e(this.clazz, "注册失败，请联系我们", e));
			return null;
		}
		Object obj = null;
		try {
			obj = ubiz.register(org, username, phone, email, password, req.getRemoteAddr());
		} catch (MyException e) {
			Response.err(rep, LogUtil.e(this.clazz, "注册失败，请联系我们", e));
			return null;
		}
		if (obj == null || !obj.equals(Env.SUCCESS)) {
			Response.err(rep, LogUtil.e(this.clazz, "注册失败，请联系我们"));
			return null;
		} else {
			Response.succ(rep, "注册成功");
			return null;
		}
	}

	public void setUbiz(TUserBiz ubiz) {
		this.ubiz = ubiz;
	}

	public void setDao(IBaseDao dao) {
		this.dao = dao;
	}

}
